package main

import (
	"context"
	"fmt"
	"net"
	"project1/day06/pb"

	"github.com/hashicorp/consul/api"
	"google.golang.org/grpc"
)

// 定义类
type Chlidren struct {
	pb.UnimplementedHelloServer // 添加这一行
}

func (this *Chlidren) mustEmbedUnimplementedSayNameServer() {
	//TODO implement me
	panic("implement me")
}

// 绑定类方法，实现接口
func (this *Chlidren) SayHello(ctx context.Context, p *pb.Person) (*pb.Person, error) {
	p.Name = "hello" + p.Name
	return p, nil
}
func main() {

	//把grpc服务，注册到consul上
	//1.初始化consul配置
	consulConfig := api.DefaultConfig()
	//2.创建consul对象
	consulClient, err := api.NewClient(consulConfig)
	if err != nil {
		fmt.Println("api.NewClient err:", err)
		return
	}
	//3.告诉consul，即将注册的服务配置信息
	registerService := api.AgentServiceRegistration{
		ID:      "bj38",
		Tags:    []string{"grpc", "consul"},
		Name:    "grpc and COnsul",
		Address: "127.0.0.1",
		Port:    8800,
		Check: &api.AgentServiceCheck{
			CheckID:  "consul grpc test",
			TCP:      "127.0.0.1:8800",
			Timeout:  "1s",
			Interval: "5s",
		},
	}

	//4.注册grpc服务到consul上
	consulClient.Agent().ServiceRegister(&registerService)
	///////////////////////////////以下为grpc的远程调用//////////////////////////////////////
	//1.初始化grpc对象
	grpcServer := grpc.NewServer()
	//2.注册服务
	pb.RegisterHelloServer(grpcServer, new(Chlidren))
	//3.设置监听，指定ip +port
	liseter, err := net.Listen("tcp", ":8800")
	if err != nil {
		fmt.Println("net.Listen err:", err)
		return
	}
	defer liseter.Close()
	fmt.Println("服务启动")
	//启动服务
	grpcServer.Serve(liseter)
}
